#include "Protocol.hpp"
#include "Sock.hpp"
#include <string>
#include <thread>
#include <unistd.h>

void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " server_port" << std::endl;
}

void HandlerRequest(int *args)
{
    int sock = *args;
    delete args;
    //业务逻辑, 做一个短服务 request-> 分析处理->构建response-> sent(response) -> colse(sock)
    // 1. 读取请求
    request_t req;
    char buffer[1024];
    ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
    if(s > 0)
    {
        buffer[s] = 0;
        std::string str = buffer;
        DeserializationRequest(str, req);

    //ssize_t s = read(sock, &req, sizeof(req));
    // if (s == sizeof(req))
    // {
        // 分析请求 && 计算结果
        response_t resp = {0, 0};

        switch (req._op)
        {
        case '+':
            resp._result = req._x + req._y;
            break;
        case '-':
            resp._result = req._x - req._y;
            break;
        case '*':
            resp._result = req._x * req._y;
            break;
        case '/':
            if (req._y == 0) // code = -1 除0错误
            {
                resp.code = -1;
            }
            else
            {
                resp._result = req._x / req._y;
            }
            break;
        case '%':
            if (req._y == 0) // code = -2 模0错误
            {
                resp.code = -2;
            }
            else
            {
                resp._result = req._x % req._y;
            }
            break;
        default: // code = -3 请求方法异常
            resp.code = -3;
            break;
        }
        // 构建链接，并且返回
        std::string json_str = serializationResponse(resp);
        write(sock, json_str.c_str(), json_str.size());
        // write(sock, &resp, sizeof(resp));
        std::cout << "服务结束！" << std::endl;
    // }
    }
    // 关闭套接字
    close(sock);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        return 1;
    }
    u_int16_t port = static_cast<u_int16_t>(atoi(argv[1]));
    int listen_sock = Sock::Socket();
    Sock::Bind(listen_sock, port);
    Sock::Listen(listen_sock);

    for (;;)
    {
        int new_sock = Sock::Accept(listen_sock);
        if (new_sock >= 0)
        {
            int *pram = new int(new_sock);
            std::thread t(HandlerRequest, pram);
            t.detach();
        }
    }
    return 0;
}
